﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using YArchitech.Controls;
using YArchitech.LIB;

namespace YArchitech.Public.Encrypt
{
	public static class Program
	{
		private static uint GetProductId(int softWareType)
		{
			if (1 == softWareType)
			{
				return 1017u;
			}
			int intSetting = IniHelper.GetIntSetting("Product", "PId", Product.DefaultConfigFile, -1);
			if (-1 != intSetting)
			{
				return (uint)intSetting;
			}
			if (Product.IsArchitecture())
			{
				return 50u;
			}
			if (Product.IsFamliyLeader())
			{
				return 38u;
			}
			if (Product.IsEDD())
			{
				return 49u;
			}
			if (Product.IsDec())
			{
				return 51u;
			}
			return 48u;
		}

		private static uint GetTrailAndAuthorizeProductId(int softWareType)
		{
			uint result;
			if (softWareType == 1)
			{
				int intSetting = IniHelper.GetIntSetting("Product", "TPId", Product.DefaultConfigFile, -1);
				if (intSetting != -1)
				{
					result = (uint)intSetting;
				}
				else
				{
					result = 1068u;
				}
			}
			else
			{
				int intSetting = IniHelper.GetIntSetting("Product", "PId", Product.DefaultConfigFile, -1);
				if (-1 == intSetting)
				{
					if (Product.IsArchitecture())
					{
						result = 50u;
					}
					else if (Product.IsFamliyLeader())
					{
						result = 38u;
					}
					else if (Product.IsEDD())
					{
						result = 49u;
					}
					else if (Product.IsDec())
					{
						result = 51u;
					}
					else if (Product.IsMEI())
					{
						result = 41u;
					}
					else if (Product.IsPC())
					{
						result = 43u;
					}
					else
					{
						result = 48u;
					}
				}
				else
				{
					result = (uint)intSetting;
				}
			}
			return result;
		}

		public static bool Init(EventHandler licenseErrorHandler)
		{
			int softWareType = Product.GetSoftWareType();
			switch (softWareType)
			{
			case 1:
				Program.m_LicenseChecker = new TrialLicenseChecker();
				break;
			case 2:
				Program.m_LicenseChecker = new AuthorizeLicenseChecker(300, 5);
				break;
			case 3:
				Program.m_LicenseChecker = new AuthorizeLicenseChecker(300, 5);
				break;
			}
			if (Program.m_LicenseChecker == null)
			{
				YJKMessageBox.Show("初始化加密锁失败，请重新安装软件！");
				return false;
			}
			Program.m_LicenseChecker.ProductId = Program.GetTrailAndAuthorizeProductId(softWareType);
			Program.m_LicenseChecker.ProductName = Product.GetSoftWareName();
			if (!Program.m_LicenseChecker.GetLicense())
			{
				YJKMessageBox.Show(Program.m_LicenseChecker.ErrorMessage);
				return false;
			}
			Program.OnInit();
			if (licenseErrorHandler != null)
			{
				LicenseChecker licenseChecker = Program.m_LicenseChecker;
				licenseChecker.LicenseError = (EventHandler)Delegate.Combine(licenseChecker.LicenseError, licenseErrorHandler);
			}
			return Program.m_LicenseChecker.CheckLicense();
		}

		public static bool LicenseValide
		{
			get
			{
				return Program.m_LicenseChecker != null && Program.m_LicenseChecker.LicenseValid;
			}
		}

		public static void Clear()
		{
			Program.OnClear();
			if (Program.m_LicenseChecker != null)
			{
				Program.m_LicenseChecker.ReleaseLicense();
			}
		}

		private static IntPtr StringToPtr(string str)
		{
			return Marshal.StringToHGlobalUni(str);
		}

		private static bool OnInit()
		{
			bool result;
			try
			{
				result = Task.Factory.StartNew<bool>(() => Program.Proxy.OnInit(new Program.D
				{
					a = (uint)Product.GetEncryptType(),
					b = (uint)Product.GetLockType(),
					c = Program.StringToPtr(Program.platform),
					d = Program.StringToPtr(Program.appName),
					e = Program.StringToPtr(Program.modelName),
					f = Program.StringToPtr(Product.GetSoftWareBuildVer()),
					g = Program.StringToPtr(Program.DateTimeToString(Program.GetInstallTime()))
				})).Result;
			}
			catch (Exception ex)
			{
				string message = ex.Message;
				result = false;
			}
			return result;
		}

		private static bool OnClear()
		{
			bool result;
			try
			{
				result = Task.Factory.StartNew<bool>(() => Program.Proxy.OnClear()).Result;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		internal static string GetUpdateLastError()
		{
			return Marshal.PtrToStringUni(Program.Proxy.GetUpdateLastError());
		}

		internal static bool OnUpdate(IntPtr hwnd)
		{
			bool result;
			try
			{
				Program.D data = new Program.D
				{
					a = (uint)Product.GetEncryptType(),
					b = (uint)Product.GetLockType(),
					c = Program.StringToPtr(Program.platform),
					d = Program.StringToPtr(Program.appName),
					e = Program.StringToPtr(Program.modelName),
					f = Program.StringToPtr(Product.GetSoftWareBuildVer()),
					g = Program.StringToPtr(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
				};
				result = Convert.ToBoolean(Program.Proxy.CheckAppUpdate(hwnd, data, Program.StringToPtr(Product.InstallLocation)));
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private static DateTime GetInstallTime()
		{
			DateTime result = DateTime.Now;
			string setting = IniHelper.GetSetting("Install", "InstallTime", Program.installTimeFile, "");
			bool flag = string.IsNullOrEmpty(setting);
			if (!flag)
			{
				result = Program.StringToDateTime(setting);
			}
			if (!File.Exists(Program.installTimeFile) || flag)
			{
				IniHelper.WriteSetting("Install", "InstallTime", Program.DateTimeToString(DateTime.Now), Program.installTimeFile);
			}
			return result;
		}

		private static string DateTimeToString(DateTime dt)
		{
			return dt.ToString("yyyy-MM-dd HH:mm:ss");
		}

		private static DateTime StringToDateTime(string str)
		{
			DateTime result;
			try
			{
				result = DateTime.Parse(str);
			}
			catch
			{
				result = DateTime.Now;
			}
			return result;
		}

		private static LicenseChecker m_LicenseChecker = null;

		private static string appName = IniHelper.GetSetting("Product", "AppName", Product.DefaultConfigFile, "BIMSpace2018");

		private static string modelName = IniHelper.GetSetting("Product", "ModelName", Product.DefaultConfigFile, "HYRME2018");

		private static string platform = IniHelper.GetSetting("StartUp", "PlatformName", Product.DefaultConfigFile, "");

		private static string installTimeFile = Path.Combine(Product.WorkingLocation, "U0053923.ini");

		private struct D
		{
			internal uint a;

			internal uint b;

			internal IntPtr c;

			internal IntPtr d;

			internal IntPtr e;

			internal IntPtr f;

			internal IntPtr g;
		}

		private class Proxy
		{
			[DllImport("hyhttp.dll", CharSet = CharSet.Auto, EntryPoint = "#1")]
			internal static extern bool OnInit(Program.D data);

			[DllImport("hyhttp.dll", CharSet = CharSet.Auto, EntryPoint = "#2")]
			internal static extern bool OnClear();

			[DllImport("UpdateBase.dll")]
			public static extern byte CheckAppUpdate(IntPtr hWnd, Program.D data, IntPtr root);

			[DllImport("UpdateBase.dll")]
			public static extern IntPtr GetUpdateLastError();
		}
	}
}
